// packageA/pages/indexnian/qrcode/qrcode.js
var common = require("../../../../public.js");
const QRCode = require('../../../../utils/weapp-qrcodedraw.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgCard: '',  //卡片背景
    myStyle: '', //动态样式，加到伪类元素中
    imgs: '',   //二维码图片
    pics: '', //利用canvas处理圆角的卡片
    userDate: {},
    num: 0,
    imagePath: '',
    // 存储定时器
    setInter: '',
    isLoading:false ,  //定义一个加载标识默认没刷新
  },

  /**
   * 生命周期函数--监听页面加载
   */
  goBack() {
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2]; //上一个页面
    // 从朋友圈进入的时候，页面栈为空，这里需要判断是否有上个页面
    if (prevPage) {
      wx.navigateBack({
        delta: 1
      })
    } else {
      wx.redirectTo({
        url: '/pages/index/index',
      })
    }
  },
  // 调整画布大小
  setCanvasSize: function () {
    var size = {};
    try {
      var res = wx.getSystemInfoSync();
      var scale = 750 / 300;//不同屏幕下canvas的适配比例；设计稿是750宽
      var width = res.windowWidth / scale;
      var height = width;//canvas画布为正方形
      size.w = width;
      size.h = height;
    } catch (e) {
      console.log("获取设备信息失败" + e);
    }
    return size;
  },
  createQrCode: function (canvasId, cavW, cavH, datas) {
    let ct = Date.parse(new Date())
    console.log(datas.orderNo, "打印datas")
    let url = 'feiyangstore/nianCards=' + '&cardId:' + datas.orderNo
    console.log('当前生成时间是。。。。', ct)
    //调用插件中的draw方法，绘制二维码图片
    QRCode.api.draw(url, canvasId, cavW, cavH);
    setTimeout(() => { this.canvasToTempImage(); }, 500);
  },
  canvasToTempImage: function () {
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: 'mycanvas',
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        console.log('生成临时图片路径。。。。', tempFilePath);
        that.setData({
          imgs: tempFilePath,
        });
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  autoRefresh: function () {
    let that = this;
    let size = that.setCanvasSize();//动态设置画布大小
    that.qrcode(size)

    //定义定时器
    that.data.setInter = setInterval(function () {
      that.setData({
        imgs: ''
      })
      console.log('定时一次', Date.parse(new Date()))
      that.qrcode(size)
      // that.createQrCode("mycanvas", size.w, size.h)

    }, 1000 * 60);
  },
  onLoad: function (options) {
    var that = this
    let capsule = wx.getMenuButtonBoundingClientRect()
    this.setData({
      height: capsule.height,
      top: capsule.top,
      storeId: options.id,
      imgCard: options.imgCard ? options.imgCard : '',
      cardId: options.cardId ? options.cardId : '',
      productId: options.productId ? options.productId : '',
      pid_name: options.pid_name ? options.pid_name : '',
      productName: options.productName ? options.productName : '',
      imgurl: options.imgurl ? options.imgurl : '',
      originalPrice: options.originalPrice ? options.originalPrice : '',
      productType: options.productType
    })
    

  },


  qrcode(size) {
    var that = this
    // 设置一个二维码刷新加载等待标识
    that.setData({
      isLoading:true  //没有请求到接口就显示刷刷新中
    })
    var temp = {
      userId: that.data.userInfo.id,
      ticketId: that.data.productId,
      cardId: that.data.cardId,
      token: that.data.token
    }

    common.post('/ticketOrder/buyCardProduct', temp, res => {
      if (res.status === 200) {
        that.setData({
          userDate: res.data,
        }, () => {
          that.createQrCode("mycanvas", size.w, size.h, res.data) //先生成一次
        })
      } else {
        common.showRequestErrMsg(res)
      }
    },()=>{
      that.setData({
        isLoading:false  //请求到接口关闭加载
      })
    })
  },

  onShow() {
    var that = this
    common.getLocalUserInfo(function (success, data) {
      if (success) {
        that.setData({
          userInfo: data.user,
          token: data.token
        }, function () {
          this.autoRefresh()
          this.cardsList_two()
        })
      } else {
        that.setData({
          userInfo: null,
          token: '',
        })
      }
    }, true)


  },


  // 免预约用户个人信息

  // 获取产品
  // 会员卡详情下面的列表会员卡可享权益    
  cardsList_two() {
    var that = this
    common.get('/userAnnualCard/getCardProductListForApplets',
      {
        cardId: that.data.cardId,
        productType: that.data.productType,
        userId: that.data.userInfo.id,
        token: that.data.token
      }, res => {
        if (res.status === 200) {
          var time = res.data.find(item => item.productId == that.data.productId)
          console.log(time, '到了')
          var jsonDa = JSON.stringify(time.enterInvoiceExplain).replace(/<img/gi, "<img class='richImg'style='width:auto!important;height:auto!important;max-height:100%;width:100%;'");
          //遍历得到的数据，给img添加CSS和style
          var newResData = JSON.parse(jsonDa);
          that.setData({
            detail: time,
            newResData,
            html: time.enterInvoiceExplain
          })
        } else {
          common.showRequestErrMsg(res)
        }

      })
  },



cardsList_two(){
  var that = this
    common.get('/userAnnualCard/getCardProductListForApplets', 
    {
      cardId:that.data.cardId, 
      productType:that.data.productType,
      userId:that.data.userInfo.id,
      token:that.data.token
    }, res => {
      if (res.status === 200) {
        var time = res.data.find(item=>item.productId==that.data.productId)
        console.log(time,'到了')
        var jsonDa = JSON.stringify(time.enterInvoiceExplain).replace(/<img/gi, "<img class='richImg'style='width:auto!important;height:auto!important;max-height:100%;width:100%;'");
        //遍历得到的数据，给img添加CSS和style
        var newResData = JSON.parse(jsonDa);
         that.setData({
          detail:time,
          newResData,
          html:time.enterInvoiceExplain 
         }) 
      } else {
        common.showRequestErrMsg(res)
      }
  })
},
//  监听页面卸载清除定时器
onUnload(){
  var that = this
  clearInterval(that.data.setInter)
}


})